<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="user-scalable=0">
    <title>贪吃蛇</title>
    <style>
        * {
            margin: 0px;
            padding: 0px;
        }

        .description {
            position: fixed;
            top: 50px;
            left: 20px;
            color: blue;
        }

        .description p {
            color: red;
        }

        #map {
            position: relative;
            top: 10px;
            left: 10px;
            width: 800px;
            height: 600px;
            background-color: #ccc;
            margin: 20px auto;

        }

        .key {
            position: relative;
            text-align: center;
        }

        .key .stop {
            position: absolute;
            bottom: 0px;
            right: 14%;
            width: 100px;
            height: 100px;
            font-size: 80px;
            background-color: darkorange;
            line-height: 102px;
        }

        .key .reflush {
            background:  url("./images/reflush.jpg");
            position: absolute;
            bottom: 0px;
            left: 14%;
            width: 100px;
            height: 100px;
            font-size: 40px;
            line-height: 100px;
            background-size: contain;
        }

        .key button {
            height: 60px;
            width: 120px;
            font-size: 40px;
            background-color: darkgreen;
        }

    </style>
</head>

<body>
    <div class="description">
        <p>PC端：</p>
        &nbsp方向键</br>
        &nbsp空格键</br>
    </div>
    <div id="map"></div>
    <div class="key">
        <button class="direction-button reflush"></button>
        <button class="direction-button stop">⏸️</button>
        <button class="direction-button up-button">⬆️</button>
        <div>
            <button class="direction-button left-button">⬅️</button>
            <button class="direction-button down-button">⬇️</button>
            <button class="direction-button right-button">➡️</button>
        </div>
    </div>
    <script src="common.js"></script>
    <script>
        var map = my$("map");
        //封装Food的自调用函数
        (function (window) {
            //用一个数组保存食物对象
            var element = [];
            //食物都构造函数
            function Food(width, height, color) {
                this.width = width || 20;
                this.height = height || 20;
                this.backgroundColor = color || "green";
            };
            //食物的初始化方法
            Food.prototype.inti = function () {
                remove();
                var div = document.createElement("div");
                div.style.position = "absolute";
                div.style.width = this.width + "px";
                div.style.height = this.height + "px";
                div.style.backgroundColor = this.backgroundColor;

                //用随机数确定位置 并给到实例对象
                var x = Math.floor(Math.random() * 40) * this.width;
                this.x = x;
                var y = Math.floor(Math.random() * 30) * this.height;
                this.y = y;
                div.style.left = x + "px";
                div.style.top = y + "px";

                //将食物放到map中去 同时也保存备份
                map.appendChild(div);
                element.push(div);
            };
            function remove() {
                for (var i = 0; i < element.length; i++) {
                    var far = element[i].parentNode;
                    far.removeChild(element[i]);
                    element.splice(i, 1);
                }
            }
            window.Food = Food;
        }(window));

        //封装Snake的自调用函数
        (function (window) {

            //存放组成蛇身体的盒子
            var bodyElement = [];

            //蛇的构造函数
            function Snake(food, map, direction) {
                this.that = this;
                this.food = food;
                this.map = map;
                this.direction = direction || "right";
                this.width = food.width;
                this.height = food.height;

                //蛇身体的初始样式
                this.bodyStyle = [
                    { x: 3, y: 5, backgroundColor: "red" },
                    { x: 2, y: 5, backgroundColor: "yellow" },
                    { x: 1, y: 5, backgroundColor: "yellow" }
                ];
            };

            //蛇的初始化
            Snake.prototype.inti = function () {
                for (var i = 0; i < this.bodyStyle.length; i++) {
                    var div = document.createElement("div");
                    div.style.position = "absolute";
                    div.style.left = this.bodyStyle[i]["x"] * this.width + "px";
                    div.style.top = this.bodyStyle[i]["y"] * this.height + "px";
                    div.style.width = this.width + "px";
                    div.style.height = this.height + "px";
                    div.style.backgroundColor = this.bodyStyle[i]["backgroundColor"];

                    bodyElement.push(div);
                    this.map.appendChild(div);
                }
            }

            //蛇的自动移动  -------------------------思路是：让样式对象的数组向后环移  让后面的对象具有前面的坐标！！！！
            Snake.prototype.autoMove = function () {

                //保存上一次移动删掉的最后一个盒子样式对象 用于吃到食物后增加盒子
                var eatFood = {};

                var timeId = setInterval(function () {

                    //复制蛇头对象
                    var newStyle = {};
                    for (var key in this.bodyStyle[0]) {
                        newStyle[key] = this.bodyStyle[0][key];
                    }
                    //将蛇头对象压入数组前面
                    this.bodyStyle.unshift(newStyle);
                    //删除数组中最后一个对象
                    eatFood = this.bodyStyle.pop();


                    //修改蛇头坐标
                    switch (this.direction) {
                        case "bottom": this.bodyStyle[0]["y"] += 1; break;
                        case "top": this.bodyStyle[0]["y"] -= 1; break;
                        case "left": this.bodyStyle[0]["x"] -= 1; break;
                        case "right": this.bodyStyle[0]["x"] += 1; break;
                    }

                    //检查下一步是否超出边界
                    if (this.bodyStyle[0]["x"] < 0 || this.bodyStyle[0]["x"] > 39) {
                        clearInterval(timeId);
                        alert("GG!");
                    }
                    if (this.bodyStyle[0]["y"] < 0 || this.bodyStyle[0]["y"] > 29) {
                        clearInterval(timeId);
                        alert("GG!");
                    }

                    //如果下一步撞到食物
                    if ((this.bodyStyle[0]["x"] == this.food.x / this.width) &&
                        (this.bodyStyle[0]["y"] == this.food.y / this.height)) {
                        //增加盒子样式对象----------------------------------------------------------------盒子样式对象
                        this.bodyStyle.push(eatFood);

                        //增加盒子 其他样式会在后面循环中统一设置
                        var div = document.createElement("div");
                        div.style.position = "absolute";
                        div.style.width = this.width + "px";
                        div.style.height = this.height + "px";

                        //新增盒子压入盒子数组--------------------------------------------------------------盒子对像
                        bodyElement.push(div);
                        this.map.appendChild(div);//-------------------------------------------------------盒子加入map
                        //刷新食物
                        this.food.inti();
                    }
                    //判断是否吃到自己 4个以上的样式才可能吃到自己
                    for (var j = 4; j < this.bodyStyle.length; j++) {
                        if ((this.bodyStyle[j]["x"] == this.bodyStyle[0]["x"]) && (this.bodyStyle[j]["y"] == this.bodyStyle[0]["y"])) {
                            clearInterval(timeId);
                            alert("eat yourself!");
                        }
                    }

                    //

                    //修改第二个 样式对象的颜色
                    this.bodyStyle[1]["backgroundColor"] = this.bodyStyle[this.bodyStyle.length - 1]["backgroundColor"];
                    //将样式对应到盒子
                    for (var i = 0; i < bodyElement.length; i++) {
                        bodyElement[i].style.left = this.bodyStyle[i]["x"] * this.width + "px";
                        bodyElement[i].style.top = this.bodyStyle[i]["y"] * this.height + "px";
                        bodyElement[i].style.backgroundColor = this.bodyStyle[i]["backgroundColor"];
                    }

                }.bind(this.that), 150);
                window.timeId = timeId;
            }

            window.Snake = Snake;
        }(window));

        //键盘方向键检测
        document.onkeydown = function (ev) {
            var kc = ev.keyCode;
            console.log(kc);
            //空格键暂停
            if (kc == 32) {
                alert("pause!!");
            }
            //不能往回走 往回走的按键无效
            if ((snake.direction == "right" && kc == 37) || (snake.direction == "top" && kc == 40) ||
                (snake.direction == "bottom" && kc == 38) || (snake.direction == "left" && kc == 39)) {
                return;
            }

            switch (kc) {
                case 38: snake.direction = "top"; break;
                case 40: snake.direction = "bottom"; break;
                case 37: snake.direction = "left"; break;
                case 39: snake.direction = "right"; break;
            }
        };

        // 页面方向点击事件
        var directionButtons = document.getElementsByClassName("direction-button")
        for (var i = 0; i < directionButtons.length; i++) {
            directionButtons[i].onclick = function (ev) {
                var classList = ev.target.classList;
                var kc = 0;
                if (classList.contains("up-button")) {
                    console.log("up");
                    kc = 38;
                    console.log(kc);
                } else if (classList.contains("down-button")) {
                    console.log("down");
                    kc = 40;
                } else if (classList.contains("left-button")) {
                    console.log("left");
                    kc = 37;
                } else if (classList.contains("right-button")) {
                    console.log("right");
                    kc = 39;
                } else if(classList.contains("stop")) {
                    alert("pause!!")
                } else {
                    window.location.reload()
                }
                //不能往回走 往回走的按键无效
                if ((snake.direction == "right" && kc == 37) || (snake.direction == "top" && kc == 40) ||
                    (snake.direction == "bottom" && kc == 38) || (snake.direction == "left" && kc == 39)) {
                    return;
                }

                switch (kc) {
                    case 38: snake.direction = "top"; break;
                    case 40: snake.direction = "bottom"; break;
                    case 37: snake.direction = "left"; break;
                    case 39: snake.direction = "right"; break;
                }
            }
        }

        //游戏初始化函数
        (function (window) {

            function Game() {
            }
            Game.prototype.inti = function () {
                var food = new Food();
                food.inti();
                var snake = new Snake(food, map);
                window.snake = snake;
                snake.inti();
                snake.autoMove();
            }
            window.Game = Game;
        }(window));

        var game = new Game();
        game.inti();



    </script>

</body>

</html>